package com.yxjx.duoxue.payment;

import java.io.IOException;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.yxjx.duoxue.BaseActionBarActivity;
import com.yxjx.duoxue.JumpActivity;
import com.yxjx.duoxue.PageLoading;
import com.yxjx.duoxue.R;
import com.yxjx.duoxue.Yx;
import com.yxjx.duoxue.dao.Dao;
import com.yxjx.duoxue.datamodel.DMCoupon;
import com.yxjx.duoxue.datamodel.DMObject;
import com.yxjx.duoxue.datamodel.DMOrder;
import com.yxjx.duoxue.datamodel.DMProduct;
import com.yxjx.duoxue.global.Globals;
import com.yxjx.duoxue.network.MsgCode;
import com.yxjx.duoxue.network.NwUtils;
import com.yxjx.duoxue.network.UserLoginResponse;
import com.yxjx.duoxue.network.UserReg;
import com.yxjx.duoxue.payment.datamodel.DMKidInfoRefObject;
import com.yxjx.duoxue.utils.UIHelper;
import com.yxjx.duoxue.utils.Utils;
import com.yxjx.duoxue.ad.AdPageActivity;
import com.yxjx.duoxue.course.CourseListActivity;
import com.yxjx.duoxue.course.CourseOrderExtraInfo;
import com.yxjx.duoxue.course.datamodel.CouponListWrapper;
import com.yxjx.duoxue.customview.MyProgressDialog;
import com.yxjx.duoxue.customview.YxRadioGroup;

public class OrderSubmitActivity extends BaseActionBarActivity {

	private static final int MSG_SUBMIT_ORDER = 1;
	private static final int MSG_JUMP_TO_PAYMENT = 2;
	private static final int MSG_LOAD_KID_LABELS_AND_COURSE_TYPES = 3;

	private static final int REQ_CODE_SELECT_COUPON = 1;
	public static final int REQ_CODE_EDIT_KID_INFO = 2;

	private int lastCount;
	private EditText orderPhone;
	private YxRadioGroup orderSex;
	private EditText orderContact;

	private ProgressDialog dialog = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fragment_order_submit);
		customizeActionBarTitle("提交订单");
		
		showLoading(true);
		

	}

	private CouponListWrapper avaiableCoupons;

	private void requestNecessaryData() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				// 可用优惠劵
				avaiableCoupons = requestAvailableCoupons();
//				 尝试加载全部课程类别信息
//				PageLoading.getCourseCategory(OrderSubmitActivity.this);
				// 尝试获取学生特点label全集
				JSONObject jo = new JSONObject();
				try {
					jo.put("date", System.currentTimeMillis());
					UserReg.getUserKids(jo, OrderSubmitActivity.this, true);
				} catch (JSONException e) {
					e.printStackTrace();
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				} catch (ClientProtocolException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					mHandler.sendEmptyMessage(MSG_LOAD_KID_LABELS_AND_COURSE_TYPES);
				}
			}
		}).start();
	}
	
	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_LOAD_KID_LABELS_AND_COURSE_TYPES:
				kidsConfiguration.update();
				// 更新是否显示选择优惠劵
				if (avaiableCoupons == null || avaiableCoupons.size() == 0) {
					findViewById(R.id.order_price_off_root).setVisibility(View.GONE);
					findViewById(R.id.order_price_off_root_above).setVisibility(View.GONE);
				}
				
				// FIXME: 弹出后IME不会弹出来！！
				UIHelper.resetScroll(OrderSubmitActivity.this, R.id.scrollView1);
				UIHelper.requestFocus(kidsConfiguration, R.id.child_name);
				showLoading(false);
				break;
			default:
				break;
			}
		};
	};
	
	@Override
	protected void onResume() {
		super.onResume();
		customizeUI();
		requestNecessaryData();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putSerializable(Yx.KEY_PRODUCT_OBJECT, product);
	}
	
	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		if (getIntent() == null) {
			return;
		} else {
			Serializable savedObject = savedInstanceState.getSerializable(Yx.KEY_PRODUCT_OBJECT);
			if (savedObject != null) {
				getIntent().putExtra(Yx.KEY_PRODUCT_OBJECT, savedObject);
			}
		}
	}
	
	private void customizeUI() {
		
		if (getIntent() == null || getIntent().getExtras() == null) {
			finish();
			return;
		}
		
		product = (DMProduct) getIntent().getExtras().getSerializable(
				Yx.KEY_PRODUCT_OBJECT);
		lastCount = 1;

		minusButton = findViewById(R.id.minus);
		plusButton = findViewById(R.id.plus);
		productNumberText = (EditText) findViewById(R.id.order_number);
		
		kidsConfiguration = (OrderKidsConfigurationView) findViewById(R.id.kids_info);

		minusButton.setOnClickListener(mClickListener);
		plusButton.setOnClickListener(mClickListener);
		UIHelper.setClickListener(findViewById(R.id.root), R.id.submit,
				mClickListener);
		UIHelper.setClickListener(findViewById(R.id.root),
				R.id.scroll_internal, mClickListener);
		UIHelper.setClickListener(findViewById(R.id.root),
				R.id.order_price_off_root, mClickListener);

		// text变化则同步更新button的状态
		productNumberText.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
				int nowCount = 0;
				if (!UIHelper.isEmpty(arg0.toString())) {
					nowCount = Integer.valueOf(arg0.toString());
				}
				if (nowCount <= 0) {
					minusButton.setEnabled(false);
				} else if (nowCount >= 9999) {
					plusButton.setEnabled(false);
				} else {
					minusButton.setEnabled(true);
					plusButton.setEnabled(true);
				}
				if (lastCount != nowCount) {
					UIHelper.setText(findViewById(R.id.order_number),
							R.id.order_number, "" + nowCount);
					UIHelper.setText(findViewById(R.id.order_total_price),
							R.id.order_total_price, product.getDiscountPrice()
									* nowCount + "元");
				}

			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {
				String lastText = arg0.toString();
				if (!UIHelper.isEmpty(lastText)) {
					lastCount = Integer.valueOf(lastText);
				}
			}

			@Override
			public void afterTextChanged(Editable arg0) {

			}
		});

		// 初始化状值
		UIHelper.setText(findViewById(R.id.order_single_price),
				R.id.order_single_price, product.getDiscountPrice() + "元");
		UIHelper.setText(findViewById(R.id.order_number), R.id.order_number, ""
				+ lastCount);
		UIHelper.setText(findViewById(R.id.order_total_price),
				R.id.order_total_price, product.getDiscountPrice() * lastCount
						+ "元");
		UIHelper.setText((TextView) findViewById(R.id.order_title),
				product.getProductName());

		UserLoginResponse ulRsp = UserLoginResponse.getInstance(this);
		orderContact = (EditText) findViewById(R.id.order_contact);
		orderSex = (YxRadioGroup) findViewById(R.id.parent_sex);
		orderSex.customizeLabels();
		orderPhone = (EditText) findViewById(R.id.order_phone);
		if (ulRsp != null) {
			UIHelper.setText(orderContact, "");
			UIHelper.setText(orderPhone, ulRsp.getPhoneNumber());
		}

		orderPhone.setOnEditorActionListener(new OnEditorActionListener() {
			@Override
			public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) {
				hideIME(orderPhone);
				mClickListener.onClick(findViewById(R.id.submit));
				return false;
			}
		});
		
		tryUpdateActualPrice();
	}
	
	private void showLoading(final boolean showing) {
		findViewById(R.id.scrollView1).post(new Runnable() {
			@Override
			public void run() {
				findViewById(R.id.loading).setVisibility(showing ? View.VISIBLE : View.INVISIBLE);
				findViewById(R.id.root).setVisibility(showing ? View.INVISIBLE : View.VISIBLE);
			}
		});
	}
	
	public void showAgreement(View view) {
		Intent intentNew = new Intent(this, AdPageActivity.class);
		intentNew.putExtra(Yx.KEY_TITLE, "多学用户付款协议");
		intentNew.putExtra(Yx.KEY_URL, NwUtils.URL_PAY_AGREEMENT);
		startActivity(intentNew);
	}

	private View.OnClickListener mClickListener = new OnClickListener() {
		@Override
		public void onClick(View arg0) {
			switch (arg0.getId()) {
			case R.id.submit:
				String phoneNum = UIHelper.getEditText(orderPhone,
						R.id.order_phone);
				String contactName = UIHelper.getEditText(orderContact,
						R.id.order_contact);
				int parentSex = orderSex.getSelectedIndex();
				
				extraInfo = new CourseOrderExtraInfo();
				// extra info
				if (kidsConfiguration.getVisibility() == View.GONE) {
					extraInfo.setIsShow(0);
				} else {
					extraInfo.setIsShow(1);
					String childName = UIHelper.getEditText(kidsConfiguration, R.id.child_name);
					if (UIHelper.isEmpty(childName)) {
						UIHelper.showTips(arg0, "学生姓名不能为空");
						childName = "";
						return;
					}
					
					
					YxRadioGroup childSexView = (YxRadioGroup) kidsConfiguration.findViewById(R.id.child_sex);
					int childSex = 0;
					childSex = childSexView.getSelectedIndex();
					
					if (childSex != 1 && childSex != 2) {
						UIHelper.showTips(arg0, "请选择学生性别");
						return;
					}
					
					extraInfo.setKidsDetailIdString(kidsConfiguration.getSelectedLablesId());
					extraInfo.setKidsName(childName);
					extraInfo.setKidsSex(childSex);
					extraInfo.setStudentBirthYear(kidsConfiguration.getSelectedYear());
					extraInfo.setStudentBirthMonth(kidsConfiguration.getSelectedMonth());
					
					if (!kidsConfiguration.isValidBirthDay()) {
						UIHelper.showTips(arg0, "请选择学生出生年月");
						return;
					}
				}
				
				if (UIHelper.isEmpty(contactName)) {
					UIHelper.showTips(arg0, "联系人姓名不能为空");
					return;
				}
				if (parentSex != 1 && parentSex != 2) {
					UIHelper.showTips(arg0, "请选择联系人性别");
					return;
				}
				if (!Utils.isMobileNumber(phoneNum)) {
					UIHelper.showTips(arg0, "手机号为空或者格式错误");
					return;
				}
				
				
				handler.sendEmptyMessage(MSG_SUBMIT_ORDER);
				break;
			case R.id.plus:
				String text = UIHelper.getEditText(
						findViewById(R.id.order_number), R.id.order_number);
				int lastNum = UIHelper.str2Int(text);
				UIHelper.setText(productNumberText, "" + (lastNum + 1));
				break;
			case R.id.minus:
				text = UIHelper.getEditText(findViewById(R.id.order_number),
						R.id.order_number);
				lastNum = UIHelper.str2Int(text);
				UIHelper.setText(productNumberText, "" + (lastNum - 1));
				break;
			case R.id.scroll_internal:
				hideIME(arg0);
				break;
			case R.id.order_price_off_root:
				selectCoupon();
				break;
			default:
				mBaseClickListener.onClick(arg0);
				break;
			}
		}
	};

	private CourseOrderExtraInfo extraInfo;
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_SUBMIT_ORDER:
				final String contactName = UIHelper.getEditText(orderContact,
						R.id.order_contact);
				final String phoneNum = UIHelper.getEditText(orderPhone,
						R.id.order_phone);
				final UserLoginResponse ulRsp = UserLoginResponse
						.getInstance(getApplicationContext());
				
				new Thread(new Runnable() {
					@Override
					public void run() {
						DMOrder order = null;
						try {
							try {
								order = UserReg.requestCourseOrder(
										getApplicationContext(), ulRsp,
										product, selectedCoupon, contactName,
										phoneNum, orderSex.getSelectedIndex(), extraInfo);
							} catch (ClientProtocolException e) {
								e.printStackTrace();
							} catch (JSONException e) {
								e.printStackTrace();
							} catch (IOException e) {
								e.printStackTrace();
							}
						} finally {
							if (dialog != null) {
								dialog.dismiss();
								dialog = null;
							}
						}
						if (order == null
								|| order.getRspCode().getCode() != MsgCode.SUCCESS) {
							UIHelper.showTips(
									orderPhone,
									order == null ? "发生未知错误" : MsgCode
											.descFor(order.getRspCode()));
						} else {
							handler.sendMessage(handler.obtainMessage(
									MSG_JUMP_TO_PAYMENT, order));
						}
					}
				}).start();
				dialog = MyProgressDialog.show(OrderSubmitActivity.this, "",
						"正在提交订单");
				break;
			case MSG_JUMP_TO_PAYMENT:
				Intent intent = new Intent(getApplicationContext(),
						PaymentSubmitActivity.class);
				DMOrder order = (DMOrder) msg.obj;
				intent.putExtra(Yx.KEY_ORDER_OBJECT, order);
				intent.putExtra(Yx.EXTRA_COUPON_OBJECT, selectedCoupon);
				startActivity(intent);
				// OrderSubmitActivity.this.setResult(RESULT_OK);
				OrderSubmitActivity.this.finish();
				break;
			default:
				break;
			}
		};
	};
	private EditText productNumberText;
	private View plusButton;
	private View minusButton;
	private DMProduct product;
	private DMCoupon selectedCoupon;
	private OrderKidsConfigurationView kidsConfiguration;

	private void selectCoupon() {
		Intent intent = new Intent(this, CouponListActivity.class);
		intent.putExtra(Yx.EXTRA_COUPON_OBJECT, selectedCoupon);
		intent.putExtra(Yx.EXTRA_COUPON_LIST, avaiableCoupons);
		startActivityForResult(intent,
				REQ_CODE_SELECT_COUPON);
	}

	@Override
	protected void onActivityResult(int reqCode, int resultCode, Intent data) {
		if (reqCode == REQ_CODE_SELECT_COUPON) {
			switch (resultCode) {
			case RESULT_OK:
				selectedCoupon = (DMCoupon) data
						.getSerializableExtra(Yx.EXTRA_COUPON_OBJECT);
				tryUpdateActualPrice();
				break;
			default:
				break;
			}
		} else if (reqCode == REQ_CODE_EDIT_KID_INFO) {
			switch (resultCode) {
			case RESULT_OK:
				DMKidInfoRefObject kidInfo = (DMKidInfoRefObject) data
						.getSerializableExtra(KidInfoEditActivity.KEY_KID_INFO_TOTAL);
				kidsConfiguration.setKidInfoTotal(kidInfo);
				break;
			default:
				break;
			}
		}
	}

	private void tryUpdateActualPrice() {
		if (selectedCoupon == null) {
			return;
		}
		findViewById(R.id.order_me_arrow).setVisibility(View.GONE);
		int totalPrice = product.getDiscountPrice();
		int offPrice = selectedCoupon.getCouponPrice();
		int actualPrice = totalPrice - offPrice;
		UIHelper.setText((TextView) findViewById(R.id.order_price_off),
				"－" + offPrice + "元");
		UIHelper.setText(
				(TextView) findViewById(R.id.order_total_price), ""
						+ actualPrice + "元");
	}
	
	public void editKidInfo() {
		Intent intent = new Intent(this, KidInfoEditActivity.class);
		
		ClientUserKidsDTS extra = Dao.getUserKidInfo(getApplicationContext());
		intent.putExtra(KidInfoEditActivity.KEY_KID_INFO_TOTAL, DMKidInfoRefObject.from(this, extra));
		startActivityForResult(intent, REQ_CODE_EDIT_KID_INFO);
	}

	private CouponListWrapper requestAvailableCoupons() {
		JSONObject params = new JSONObject();
		long prodcutId = (product == null ? -1 : product.getId());
		try {
			params.put("productId", "" + prodcutId);
			params.put("time", System.currentTimeMillis());
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		CouponListWrapper items = null;
		try {
			items = UserReg.requestCouponList(params, OrderSubmitActivity.this);
		} catch (ClientProtocolException e1) {
			e1.printStackTrace();
		} catch (ParseException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		return items;
	}

}
